package cn.heycm.common.async;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Virtual Thread Task
 *
 * @author hey
 * @version 1.0
 * @since 2024/9/18 22:39
 */
public class Async {

    /**
     * 执行任务
     *
     * @param runnable 任务
     */
    public static void execute(Runnable... runnable) {
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (Runnable r : runnable) {
                executor.execute(r);
            }
        }
    }

    /**
     * 提交任务，并等待所有任务完成
     *
     * @param runnable 任务
     */
    public static void submit(Runnable... runnable) {
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<?>> futures = new ArrayList<>(runnable.length);
            for (Runnable r : runnable) {
                Future<?> submit = executor.submit(r);
                futures.add(submit);
            }
            for (Future<?> future : futures) {
                future.get();
            }
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
